<template>
  <div id="app" :style="embed ? 'min-height: auto; padding-bottom: 0;' : 'padding-bottom: 111px'"
  :class="{'pdbt330': $route.name==='index', 'backBlue': $route.name === 'luckyDraw', 'bgWhite': $route.name === 'rexExchange'}" v-if="visitedPage">
    <nav-menu
    v-if="$route && $route.name && !embed"
    @listenIntelligentContract="handleIntelligentContract"
    @listenWalletPermission="handleWalletPermission"
    @listenWalletLogin="handleWalletLogin"/>
    <router-view
    @listenWalletPermission="handleWalletPermission"
    @listenWalletLogin="handleWalletLogin"/>
    <footer-page
    v-if="$route
    && $route.name
    && $route.name==='index' && !embed"
    @listenCheckNode="handleCheckNode" />
    <new-footer-page
    v-if="$route
    && $route.name
    && $route.name!=='index' && !embed"
    @listenCheckNode="handleCheckNode" />
    <el-dialog
      title="Newdex"
      :close-on-click-modal="false"
      :visible.sync="chainFlyVisible"
      width="700px">
      <div class="chainFlyhybox">
        <!-- 委托账户 -->
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item prop="chainEOS" :style="$store.state.app.language === 'en' ? 'padding: 0 4px' : 'padding: 0 55px'">
            <div style="padding: 20px 0px;">
              <label style="padding-right:10px">{{$t('nav.EntrustedAccount')}}</label>
              <el-select
                v-model="chainChecked.label"
                class="chainCheck"
                @change="handleCheckOption">
                <!-- <span slot="prefix"
                  style="float: left;padding-left:15px;color:#333;">{{ chainChecked.label }}
                </span> -->
                <span slot="prefix"
                  style="float: right;">{{ chainChecked.chainType }}
                </span>
                <el-option
                  class="chainCheckOption"
                  v-for="item in wtOptions"
                  :key="item.value"
                  :value="item.value">
                  <span style="float: left; color: #333;">{{ item.label }}</span>
                  <span style="float: right;">{{ item.chainType }}</span>
                </el-option>
              </el-select>
              <el-popover
              trigger="click"
              placement="bottom"
              width="160"
              popper-class="searchDetails"
              style="padding: 0;">
                <div class="changeBrowse">
                  <div>{{$t('nav.selectBlockBrowser')}}</div>
                  <template v-for="(item, index) in chainChecked.options">
                    <p :key="index">
                      <a :href="item.url" target="_blank">
                        <img :src="item.img" alt="" :class="item.class">
                      </a>
                    </p>
                  </template>
                </div>
                <el-button slot="reference" type="primary" class="ml5 btn"> {{$t('nav.searchAccountDetail')}} </el-button>
              </el-popover>
              <div class="entrustAccount">
                <span class="fl" @click="entrustAccountShow = !entrustAccountShow">{{$t('nav.entrustCaption')}}</span>
                <div class="fl">
                  <el-collapse-transition>
                    <div v-show="entrustAccountShow">
                      <div v-if="chainChecked.name === 'EOS'">
                        <p>
                          {{$t('nav.entrustAccount1', {chain: this.chainChecked.name})}}
                          <span>
                            {{$t('nav.entrustAccount2')}}
                            <span @click="handleIocoldAction" class="jumpEosflare">{{$t('nav.newdexpocket')}}</span>
                            {{$t('nav.period')}}
                          </span>
                        </p>
                      </div>
                      <div v-else-if="chainChecked.name === 'TRON'">
                        <p>
                          {{$t('nav.tronEntrust', {chain: this.chainChecked.name})}}
                        </p>
                      </div>
                      <div v-else>
                        <p>
                          {{$t('nav.otherEntrustAccount', {chain: this.chainChecked.name})}}
                        </p>
                      </div>
                    </div>
                  </el-collapse-transition>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- 节点选择弹窗 -->
    <el-dialog
      class="scatterTitle nodeChoiceLayer"
      :title="'Newdex'"
      :close-on-click-modal="true"
      :visible.sync="nodeVisible"
      width="800px">
      <choice-node :node-visible="nodeVisible" @listenCancelNode="nodeVisible = false"/>
    </el-dialog>
    <!-- scatter授权 -->
    <el-dialog
      class="scatterTitle"
      :title="$t('nav.permission')"
      :close-on-click-modal="true"
      :visible.sync="scatterVisible"
      width="620px">
      <scatter-permission @listenScatterClose="handleScatterPermission"/>
    </el-dialog>

    <!-- 下单、撤单公告 -->
    <el-dialog
      class="upgradebox"
      title="Newdex"
      :show-close= 'true'
      :close-on-click-modal="false"
      :visible.sync="upgradeVisible"
      width="680px">
      <upgrade @listenUpgradeClose="upgradeVisible=false"/>
    </el-dialog>

    <!-- 钱包授权 -->
    <el-dialog
      class="walletTitle"
      :title="$t('wallet.promistLogin')"
      :show-close= 'true'
      :close-on-click-modal="false"
      :visible.sync="walletVisible"
      width="680px">
      <wallet-permission @listenWalletClose="walletVisible=false; walletLoginVisible=true"/>
    </el-dialog>

    <!-- 用户登录 钱包选择 -->
    <el-dialog
      class="walletLoginDiaog"
      :close-on-click-modal="false"
      :visible.sync="walletLoginVisible"
      :width="$appName === 'eosNewdex' ? '980px' : '550px'">
      <wallet-login @listenWalletLoginClose="walletLoginVisible = false" :walletLoginShow="walletLoginVisible"/>
    </el-dialog>

    <!-- 叶子钱包 多账户登录 -->
    <el-dialog
      :class="{ 'moreAccountDialog' : defaultCls, 'normalAccountDialog' : !defaultCls }"
      :show-close='!defaultCls'
      :visible.sync="moreAccountVisible"
      width="300px">
      <more-account
      @listenWalletLogin="moreAccountVisible=false;walletLoginVisible = true"
      @listenMoreAccount="handleMoreAccount"
      :moreAccountVisible="moreAccountVisible"/>
    </el-dialog>

    <!-- 多账户退出提示-->
    <div v-if="tipsLoginout">
      <tips :text="this.$t('qh.qh6')"
        :width="400"
        :showBtn = true
        :hasCancel = true
        @listenTips="handleLoginOutAll" />
    </div>

    <!-- 选择公链弹窗 -->
    <el-dialog
      class="choiceChainDiaog"
      :close-on-click-modal="false"
      :visible.sync="choiceChainVisible"
      @close="handleChoiceChainClose"
      width="850px">
      <choice-chain @listenChoiceChain="handleChoiceChain" />
    </el-dialog>
    <a href="https://bloks.io/account/newdexiocold" class="hidden" target="_blank" ref="iocold"></a>
  </div>
</template>

<script>
import Bus from '@/utils/bus';
import Io from '@/utils/socket';
import { EosModel } from '@/utils/eos/index';
import NavMenu from '@/views/layout/navmenu/Index';
import FooterPage from '@/views/layout/footer/Index';
import NewFooterPage from '@/views/layout/footer/Footer';
import ScatterPermission from '@/components/ScatterPermission';
import WalletPermission from '@/components/WalletPermission';
import MoreAccount from '@/components/MoreAccount';
import Tips from '@/components/Tips';
import WalletLogin from '@/components/WalletLogin';
import Upgrade from '@/components/Upgrade';
import ChoiceNode from '@/components/ChoiceNode';
import ChoiceChain from '@/components/ChoiceChain';
import { toFixed, getUrlParams } from '@/utils/validate';
import axios from 'axios';
import Cookies from 'js-cookie';

export default {
  name: 'App',
  data() {
    return {
      embed: false, // 是否内嵌
      visitedPage: false,
      entrustAccountShow: true, // 委托账户说明
      theme: '',
      themelist: [
        {
          name: 'theme-1B1D27',
          value: '#1B1D27',
          light: '#1B1D27'
        },
        {
          name: 'theme-278EDA',
          value: '#1B1D27',
          light: '#1B1D27'
        },
      ],
      chainFlyVisible: false,
      scatterVisible: false, // scatter 授权
      walletVisible: false, // 钱包授权
      upgradeVisible: false, // 功能暂停公告
      walletLoginVisible: false, // 钱包登录系统
      moreAccountVisible: false, // 多账户系统
      defaultCls: false, // 多账户系统展示形式， true为悬浮顶上
      tipsLoginout: false, // 退出多账户
      nodeVisible: false, // 节点选择
      choiceChainVisible: false, // 选择公链
      form: {
        chainEOS: '',
        chainBOS: '',
        chainMEETONE: '',
        chainENU: '',
        chainFIBOS: '',
        chainTELOS: '',
        chainWAX: '',
        chainLYNX: '',
      },
      rules: {
        code: [
          { required: true, message: '请输入智能合约地址', trigger: 'blur' },
        ],
      },

      // 定时器 - 清除 session 中钱包密码
      timer: null,
      timeAccountRes: null, // 定时器 - 清除获取账户余额
      timerGetLegalCurrencyPrices: null, // 定时器 - 法币估值
      wtOptions: [], // 委托账户下拉数据
      chainChecked: {
        options: []
      }, // 委托账户选中框值
      language: 'en',
      usdsList: [], // 稳定比集合
    };
  },
  components: {
    NavMenu,
    FooterPage,
    NewFooterPage,
    ScatterPermission,
    WalletPermission,
    WalletLogin,
    Upgrade,
    ChoiceNode,
    ChoiceChain,
    MoreAccount,
    Tips
  },
  watch: {
    '$store.state.app.theme': function change(val) {
      this.theme = val;
      this.handleThemeAction();
    },
    '$store.state.app.language': function change(val) {
      this.language = val;
      this.handelGetLegalCurrencyPrices();
      // this.handleGetAccountInfo();
      this.handleWeiTuoList();
      zE('webWidget', 'setLocale', this.handleLangFormatZendex(val)); // eslint-disable-line
    },
    '$store.state.app.scatter.identity': {
      handler: function listen() {
        // 获取账号会员信息
        this.handleGetAccountInfo();
        this.handleGetAccountAgreement();
        this.handleGetAccountRes();
        // 获取未读订单
        this.handleUnreadOrder();
        this.handleWeiTuoList();
      },
      deep: true,
    },
    '$store.state.app.upgradeSystem': function change(val) {
      if (val) {
        this.upgradeVisible = true;
        return;
      }
      this.upgradeVisible = false;
      this.$store.dispatch('setUpgradeSystem', false);
    },
    '$route.name': function change(val) {
      this.embed = false;
      if (val === 'embedTrade' || val === 'embedSwap') {
        this.embed = true;
      }
      this.handleGetAccountRes();
      // cnzz 站长统计
      window._czc = window._czc || []; // eslint-disable-line
      const location = window.location;
      const contentUrl = location.pathname + location.hash;
      const refererUrl = '/';
      window._czc.push(['_trackPageview', contentUrl, refererUrl]); // eslint-disable-line
      // 选择公链弹窗
      this.handleChoiceCurrent();
    },
  },
  created() {
    const rname = this.$route.name;
    if (rname === 'embedTrade' || rname === 'embedSwap') {
      this.embed = true;
    }
    // if (!locaTheme) {
    //   // 白天 与 黑夜
    //   const now = new Date();
    //   const hour = now.getHours();
    //   this.theme = hour < 17 ? 'theme-278EDA' : 'theme-1B1D27';
    //   this.handleThemeAction();
    //   return;
    // }
    // this.$store.dispatch('setHistoryData', historyData);
    this.theme = localStorage.getItem('theme') || 'theme-278EDA';
    this.handleThemeAction();
  },
  mounted() {
    Io.addListenerRefresh();
    this.language = this.$store.state.app.language;
    // 解密私钥Test
    // const data = '1540974031xiamentoponeios-839FDA46C14C4089ABAA5E000B6D5B9CPrabox';
    // const sign = EosModel.Ecc.sign(data, '5JD4dXv3RomwYpAyuCEg1G1Zdw7n9gFkJxBHbzX5xMNWKEWwPTw');
    // console.log(sign);
    // const verify = EosModel.Ecc.verify(sign, data, 'EOS5adjTYEYy4G4RksDYW3JWfddMhzS7cYUzAaGeArptUbvh1a9NX')
    // console.log(verify);
    this.visitedPage = true;
    // 获取站点公共信息
    this.handleGetCommonParam();
    /* 添加account 账户监听 */
    const scat = this.$store.state.app.scatter;
    if (scat && scat.identity) {
      Io.accountBind(scat.identity.accounts[0].name);
    }

    /*
    * ORDER_UPDATE(1, "orderupdate", "订单更新"),
    * ORDER_SUCCESS(2, "ordersuccess", "下单成功"),
    * CANCEL_SUCCESS(3, "cancelsuccess", "撤单成功"),
    * ORDER_FAIL(4, "orderfail", "下单失败"),
    * CANCEL_FAIL(5, "cancelfail", "撤单失败");
    */
    Io.addListenerOrder('start', (res) => {
      // console.log('-------------当前订单-------------'); // eslint-disable-line
      // console.log(res); // eslint-disable-line
      // console.log(res.type === 'orderupdate' || res.type === 'ordersuccess');
      if (res.type === 'ordersuccess') { // 下单成功
        this.handleGetAccountInfo();
      }
      if (res.type === 'orderupdate') { // 订单更新
        // 获取未读订单个数
        this.handleUnreadOrder();
        this.handleGetAccountInfo();
      }
      if (res.type === 'cancelsuccess') { // 撤单成功
      }
      if (res.type === 'orderfail') { // 下单失败
      }
      if (res.type === 'cancelfail') { // 撤单失败
      }
      if (res.type === 'stakedsuccess') { // 抵押成功
        this.handleGetAccountInfo();
      }
      if (res.type === 'stakedError') { // 抵押失败
      }
    });
    // 用户同意协议否？
    this.handleGetAccountAgreement();
    // 获取账号会员信息
    this.handleGetAccountInfo();
    // 获取法币估值
    this.handelGetLegalCurrencyPrices();
    // 调用节点弹窗
    Bus.$on('handleChoiceNode', (val) => {
      this.nodeVisible = val;
    });
    // 获取未读订单
    this.handleUnreadOrder();

    // 渠道统计 保存cookie
    const hrefForParams = window.location.href;
    const hrefObj = getUrlParams(hrefForParams) || {};
    if (hrefObj && hrefObj.ref) {
      Cookies.set('walletRef', hrefObj.ref, { expires: 30 }); // 保存30天
    }
    // 矿池跳转过来变更语言
    if (hrefObj && hrefObj.language) {
      this.$i18n.locale = hrefObj.language;
      this.$store.dispatch('setLanguage', hrefObj.language);
    }
    // cnzz 站长统计
    const script = document.createElement('script');
    script.async = true;
    script.type = 'text/javascript';
    script.charset = 'utf-8';
    script.src = 'https://s22.cnzz.com/z_stat.php?id=1274360520&web_id=1274360520&async=1';
    script.language = 'JavaScript';
    document.body.appendChild(script);
    // 选择公链弹窗
    this.handleChoiceCurrent();
    window.onload = (() => {
      zE('webWidget', 'helpCenter:setSuggestions', { search: 'Newdex' }); // eslint-disable-line
      zE('webWidget', 'setLocale', this.handleLangFormatZendex(this.language)); // eslint-disable-line
    })
  },
  methods: {
    handleLangFormatZendex(lan) {
      const lans = {
        en: 'en-US',
        ko: 'ko',
        'zh-CN': 'zh-cn',
        'zh-TW': 'zh-tw'
      }
      return lans[lan];
    },
    // 数字截取 - 保留小数
    handleToFixed(num, p) {
      return toFixed(num, p);
    },
    /*
    * 主题调取
    */
    handleThemeAction() {
      const themeLink = document.querySelector('link[name="theme"]');
      const target = this.themelist.find(v => v.name === this.theme);
      let path;
      if (target) {
        path = `/static/theme/${target.name}/index.css`;
        document.getElementsByTagName('body')[0].className = target.name;
        themeLink.setAttribute('href', path);
      }
    },

    /*
    * 智能合约地址
    */
    handleIntelligentContract(flag) {
      this.chainFlyVisible = flag;
    },

    /**
     * Scatter 授权
     */
    handleScatterPermission(flag) {
      this.scatterVisible = flag;
    },

    /**
     * 钱包授权
     */
    handleWalletPermission(flag) {
      this.walletVisible = flag;
    },

    /**
     * 钱包登录
     */
    handleWalletLogin(flag, offset) {
      const isOpenMoreAccount = true;
      if (this.$store.state.app.scatter.scatterFrom === 'leafwallet'
      && this.$store.state.app.scatter.identity
      && this.$store.state.app.scatter.identity.accounts.length > 0
      && this.$store.state.app.scatter.by !== 'mobileWallet'
      && isOpenMoreAccount) {
        this.moreAccountVisible = true;
        this.defaultCls = false;
        if (offset) {
          this.defaultCls = true;
        }
        return;
      }
      this.walletLoginVisible = flag;
    },
    // 多账户操作通讯
    handleMoreAccount(key) {
      this.moreAccountVisible = false;
      if (key === 'LoginOutAll') {
        this.tipsLoginout = true;
      }
      this.$forceUpdate(); // 强制更新
    },
    // 退出多账户
    handleLoginOutAll(key) {
      this.tipsLoginout = false;
      if (key === 'sure') {
        EosModel.accountLoginOut(() => {});
        const route = this.$route;
        if (route && route.meta && route.meta.isUser) {
          this.$router.push('/');
          return;
        }
        window.location.reload();
      }
    },

    /**
     * 功能暂停公告
     */
    handleUpgradeAction(flag) {
      this.upgradeVisible = flag;
    },

    // 获取站点公共信息
    handleGetCommonParam() {
      const localNode = localStorage.getItem('nodeChecked');
      const nodeobj = localNode ? JSON.parse(localNode) : { eos: null, bos: null, meetone: null };
      const nodeJson = {
        eosNode: nodeobj.eos ? nodeobj.eos.url : null,
        bosNode: nodeobj.bos ? nodeobj.bos.url : null,
        meetoneNode: nodeobj.meetone ? nodeobj.meetone.url : null,
        enuNode: nodeobj.enu ? nodeobj.enu.url : null,
        fibosNode: nodeobj.fibos ? nodeobj.fibos.url : null,
        telosNode: nodeobj.telosNode ? nodeobj.telosNode.url : null,
        waxNode: nodeobj.waxNode ? nodeobj.waxNode.url : null,
        lynxNode: nodeobj.lynxNode ? nodeobj.lynxNode.url : null,
      };
      this.$http.post('/common/getCommonParam', { params: JSON.stringify(nodeJson) }).then((res) => {
        if (res.code !== 0) {
          this.$message.error(res.msg);
          return;
        }
        this.form.chainEOS = res.chainEosAccount;
        this.form.chainBOS = res.exchangeBosAccount;
        this.form.chainMEETONE = res.exchangeMeetoneAccount;
        this.form.chainENU = res.exchangeEnuAccount;
        this.form.chainFIBOS = res.exchangeFibosAccount;
        this.form.chainTELOS = res.exchangeTelosAccount;
        this.form.chainTRON = res.tronContract;
        this.form.chainWAX = res.exchangeWaxAccount;
        this.form.chainWAX1 = res.chainWaxAccount; // 委托账户
        this.form.chainLYNX = res.exchangeLynxAccount; // 委托账户
        this.form.chainLYNX1 = res.chainLynxAccount; // 委托账户
        if (this.$appName === 'tronNewdex') {
          const address = res.tronContract;
          this.form.chainTRON1 = `${address.substring(0, 5)}...${address.substring(address.length - 5, address.length)}`;
        }
        this.handleWeiTuoList();
        const chainExchange = {
          eos: res.exchangeEosAccount,
          'chain-eos': res.chainEosAccount, // 合约账户
          bos: this.form.chainBOS,
          meetone: this.form.chainMEETONE,
          enu: this.form.chainENU,
          fibos: this.form.chainFIBOS,
          telos: this.form.chainTELOS,
          wax: this.form.chainWAX,
          'chain-wax': this.form.chainWAX1, // 合约账户
          lynx: this.form.chainLYNX,
          'chain-lynx': this.form.chainLYNX1,
        }
        this.$store.dispatch('setExchangeAccount', chainExchange); // 转账账户
        // eos 站点
        if (this.$appName === 'eosNewdex') {
          const nodeChecked = {
            eos: res.eosNode,
            bos: res.bosNode,
            meetone: res.meetoneNode,
            enu: res.enuNode,
            fibos: res.fibosNode || res.enuNode,
            telos: res.telosNode || res.eosNode,
            wax: res.waxNode,
            lynx: res.lynxNode,
            timer: null,
          }
          this.$store.dispatch('setNodeChecked', nodeChecked); // 默认节点配置
          setTimeout(() => {
            // 实时监听节点延时
            this.handleLoadingStatus();
          }, 3000);
        }
        // 查询余额接口地址存储
        localStorage.setItem('xeosApiUrl', res.xeosApiUrl);
        // rexProxy 投票节点
        localStorage.setItem('rexProxy', res.rexProxy);
        EosModel.scatterInit(this, () => {});
        if (this.$appName === 'eosNewdex') {
          EosModel.enuInit(this, () => {});
          // EosModel.lynxInit(this, () => {});
        }
        // 稳定币集合
        this.usdsList = res.stableCoinCodeList || [];
        this.$store.dispatch('setStableCode', this.usdsList);
        const chargingStatus = {
          coinConvertStatus: res.coinConvertStatus,
          // withdrawStatus: res.withdrawStatus,
          // depositStatus: res.depositStatus
        }
        this.$store.dispatch('setCoinConvertStatus', chargingStatus);
      });
    },
    // 获取余额等信息
    handleGetAccountRes() {
      if (this.$appName !== 'eosNewdex') return;
      // 设置前先清掉就定时器
      clearTimeout(this.timeAccountRes);
      const routeTitle = this.$route && this.$route.meta ? this.$route.meta.title : '';
      if (routeTitle !== 'Exchange'
      && routeTitle !== 'ramExchange'
      && routeTitle !== 'rexExchange'
      && routeTitle !== 'cpuExchange'
      && routeTitle !== 'mywallet'
      && routeTitle !== 'newpos') return;
      const accountRes = {
        net: {
          used: 0,
          max: 0,
        },
        cpu: {
          used: 0,
          max: 0,
        },
        ram: {
          used: 0,
          max: 0,
        },
        balance: 0,
        refund_request: {
          net_amount: 0,
          cpu_amount: 0,
        },
        total_resources: {
          cpu_weight: 0,
          net_weight: 0,
        },
        self_delegated_bandwidth: {
          cpu_weight: 0,
          net_weight: 0,
        },
        last_code_update: '',
      };
      const scat = this.$store.state.app.scatter
      if (scat && scat.identity) {
        const params = {
          account_name: scat.identity.accounts[0].name
        };
        EosModel.getAccount(params, (result) => {
          const res = result;
          if (!res.account_name) return;
          accountRes.ram.used = res.ram_usage;
          accountRes.ram.max = res.ram_quota;
          accountRes.cpu.used = res.cpu_limit.used;
          accountRes.cpu.max = res.cpu_limit.max;
          accountRes.net.used = res.net_limit.used;
          accountRes.net.max = res.net_limit.max;
          accountRes.balance = res.core_liquid_balance;
          accountRes.last_code_update = res.last_code_update;
          if (res.refund_request) {
            accountRes.refund_request.net_amount = res.refund_request.net_amount;
            accountRes.refund_request.cpu_amount = res.refund_request.cpu_amount;
          }
          if (res.self_delegated_bandwidth) {
            accountRes.self_delegated_bandwidth.cpu_weight = res.self_delegated_bandwidth.cpu_weight;
            accountRes.self_delegated_bandwidth.net_weight = res.self_delegated_bandwidth.net_weight;
          }
          if (res.total_resources) {
            accountRes.total_resources.cpu_weight = res.total_resources.cpu_weight;
            accountRes.total_resources.net_weight = res.total_resources.net_weight;
          }
          accountRes.producers = [];
          accountRes.proxy = '';
          if (res.voter_info) {
            accountRes.producers = res.voter_info.producers;
            accountRes.proxy = res.voter_info.proxy;
          }
          this.$store.dispatch('setAccountRes', accountRes);
        });
        this.timeAccountRes = setTimeout(() => {
          this.handleGetAccountRes();
        }, 5000);
      }
    },
    // 获取账户信息
    handleGetAccountAgreement() {
      const scatter = this.$store.state.app.scatter;
      if (scatter && scatter.identity) {
        // this.$store.dispatch('setAccountAgree', false);
        const params = {
          account: scatter.identity.accounts[0].name,
          type: scatter.identity.accounts[0].blockchain === 'eos' ? 1 : 2
        }
        this.$http.post('/account/getAccountAgreement', params).then((res) => {
          if (res.code !== 0) {
            this.$message.error(res.msg);
            return;
          }
          if (res.status === 1) {
            this.$store.dispatch('setAccountAgree', true);
          }
        });
      }
    },
    // 获取账号会员信息
    handleGetAccountInfo() {
      const scatter = this.$store.state.app.scatter;
      if (scatter && scatter.identity) {
        const params = {
          account: scatter.identity.accounts[0].name
        }
        this.$http.post('/account/getAccountInfo', params).then((res) => {
          if (res.code === 1007) {
            const info = {
              account: this.$store.state.app.scatter.identity.accounts[0].name,
              chain: this.$store.state.app.scatter.chain,
              ambassadorType: null,
              anonymous: 0,
              consumeLevel: 0,
              discountRate: 1,
              email: null,
              expireTime: null,
              isDealRemind: 0,
              isMarketRemind: 0,
              isRenew: 0,
              joinTime: null,
              language: this.$store.state.app.language,
              level: 0,
              maxLevel: 10,
              ndxStaked: 0,
              noRemindPartial: 0,
              orderTime: null,
              remainDealRemindCount: 10,
              remainDrawCount: 0,
              remainMarketRemindCount: 5,
              renewDuration: null,
              stakeLevel: 0,
              totalSaveAmount: 0,
              usedMarketRemindCount: 0,
              vipImageUrl: null,
              vipMode: 0,
              weight: 0,
              weightRatio: 0,
              remainFreeOrderCount: 1
            }
            this.$store.dispatch('setAccountInfo', info);
            this.handleReloadLevel(info)
            return;
          }
          if (res.code !== 0) {
            return;
          }
          if (res.code === 0) {
            this.$store.dispatch('setAccountInfo', res.accountInfo || {});
            this.handleReloadLevel(res.accountInfo)
          }
        });
        return;
      }
      this.$store.dispatch('setAccountInfo', {});
    },
    // 更新多账户等级
    handleReloadLevel(accountInfo) {
      const scatter = this.$store.state.app.scatter;
      if (scatter && scatter.identity) {
        const item = scatter.identity.accounts.find(v => v.name === accountInfo.account &&
        v.chain === accountInfo.chain);
        if (item) {
          item.level = accountInfo.level;
          this.$store.dispatch('setScatter', scatter);
        }
      }
    },
    // 选择节点
    handleCheckNode(flag) {
      this.nodeVisible = flag;
    },
    // 实时监听节点延时
    handleLoadingStatus() {
      const sapp = this.$store.state.app;
      const chain = sapp.scatter.chain || 'eos';
      const nodeApp = sapp.nodeChecked[chain];
      const url = nodeApp.url;
      let nodeTime = new Date().getTime();
      let nodeTip = -1;
      axios.get(`${url}/v1/chain/get_info`, {
        timeout: 5500,
      }).then(() => {
        nodeTime = new Date().getTime() - nodeTime;
        // tip 0低延迟 1一般延迟 2高延迟 3超时
        if (nodeTime < 1000) {
          nodeTip = 0;
        }
        if (nodeTime >= 1000 && nodeTime <= 5000) {
          nodeTip = 1;
        }
        if (nodeTime > 5000) {
          nodeTip = 2;
        }
        if (nodeTime > 9500) {
          nodeTip = 3;
        }
        nodeApp.tip = nodeTip
        nodeApp.time = nodeTime;
        this.handleTimerAction(20000, nodeApp, chain, sapp);
      }).catch(() => {
        nodeApp.tip = 3;
        nodeApp.time = 10000;
        this.handleTimerAction(15000, nodeApp, chain, sapp);
      });
    },
    // 实时监听节点延时- timer 定时器
    handleTimerAction(time, nodeApp, chain, sapp) {
      this.$set(sapp.nodeChecked, 'timer', new Date().getTime());
      setTimeout(() => {
        this.handleLoadingStatus();
      }, time);
    },
    // 获取法币估值
    handelGetLegalCurrencyPrices() {
      const usdsList = this.usdsList;
      let valuationCoins = ['EOS', 'BOS', 'MEETONE', 'TLOS', 'USDT', 'WAX', 'LNX'];
      valuationCoins.push(...usdsList);
      if (this.$appName === 'tronNewdex') {
        valuationCoins = ['TRX', 'USDT'];
      }
      const legalCurrency = this.$store.state.app.language === 'zh-CN' ? 'CNY' : 'USD'
      const params = {
        valuationCoins: valuationCoins.toString(),
        legalCurrency,
      }
      this.$http.get('/common/getLegalCurrencyPrices', { params }).then((res) => {
        if (res.code !== 0) {
          // this.handelGetLegalCurrencyPrices();
          return;
        }
        const prices = res.prices;
        const pricesCurrentcy = {
          legalCurrency,
          legalCurrencyForMat: legalCurrency === 'CNY' ? '¥' : '$'
        };
        valuationCoins.forEach((v, i) => {
          pricesCurrentcy[v] = prices[i] || 0;
        });
        this.$store.dispatch('setPricesCurrentcy', pricesCurrentcy);
        if (this.timerGetLegalCurrencyPrices) {
          clearTimeout(this.timerGetLegalCurrencyPrices);
        }
        this.timerGetLegalCurrencyPrices = setTimeout(() => {
          this.handelGetLegalCurrencyPrices()
        }, 10000);
      });
    },
    // 获取未读订单个数
    handleUnreadOrder() {
      const scat = this.$store.state.app.scatter;
      if (scat && scat.identity) {
        const params = {
          accountNo: scat.identity.accounts[0].name,
        }
        this.$http.post('/order/getUnReadCount', params).then((res) => {
          if (res.code !== 0) {
            this.$message.error(res.msg);
            return;
          }
          this.$store.dispatch('setBadge', res.unReadCount);
        });
      }
    },

    // 获取委托账户列表
    handleWeiTuoList(val) {
      let checked = val;
      let chain = this.$store.state.app.scatter.chain;
      this.wtOptions = [
        {
          value: 1,
          name: 'EOS',
          label: this.form.chainEOS,
          chainType: `EOS${this.$t('bosChain.chain')}`,
          options: [
            {
              name: 'bloks',
              url: `https://bloks.io/account/${this.form.chainEOS}`,
              class: 'bloks',
              img: '../static/img/entrusted/bloks.png',
            },
            {
              name: 'eosflare',
              url: `https://eosflare.io/account/${this.form.chainEOS}`,
              class: 'eosflare',
              img: '../static/img/entrusted/eosflare.png',
            },
            {
              name: 'eospark',
              url: `https://eospark.com/account/${this.form.chainEOS}`,
              class: 'eospark',
              img: '../static/img/entrusted/eospark.png',
            },
            {
              name: 'myeos',
              url: `https://eosx.io/account/${this.form.chainEOS}`,
              class: 'myeos',
              img: '../static/img/entrusted/myeos.png',
            }
          ]
        },
        {
          value: 2,
          name: 'BOS',
          label: this.form.chainBOS,
          chainType: `BOS${this.$t('bosChain.chain')}`,
          options: [
            // {
            //   name: 'eospark',
            //   url: `https://bos.eospark.com/account/${this.form.chainBOS}`,
            //   class: 'eospark',
            //   img: '../static/img/entrusted/eospark.png',
            // },
            {
              name: 'myeos',
              url: `https://bos.eosx.io/account/${this.form.chainBOS}`,
              class: 'myeos',
              img: '../static/img/entrusted/myeos.png',
            },
            {
              name: 'bloks',
              url: `https://bos.bloks.io/account/${this.form.chainBOS}`,
              class: 'bloks',
              img: '../static/img/entrusted/bloks.png',
            },
          ]
        },
        {
          value: 3,
          name: 'TELOS',
          label: this.form.chainTELOS,
          chainType: `TELOS${this.$t('bosChain.chain')}`,
          options: [
            {
              name: 'myeos',
              url: `https://telos.eosx.io/account/${this.form.chainTELOS}`,
              class: 'myeos',
              img: '../static/img/entrusted/myeos.png',
            },
          ]
        },
        {
          value: 4,
          name: 'MEETONE',
          label: this.form.chainMEETONE,
          chainType: `MEETONE${this.$t('bosChain.chain')}`,
          options: [
            {
              name: 'myeos',
              url: `https://meetone.eosx.io/account/${this.form.chainMEETONE}`,
              class: 'myeos',
              img: '../static/img/entrusted/myeos.png',
            },
          ]
        },
        // {
        //   value: 4,
        //   name: 'ENU',
        //   label: this.form.chainENU,
        //   chainType: `ENU${this.$t('bosChain.chain')}`,
        //   options: [
        //     {
        //       name: 'enu',
        //       url: `http://enumivo.qsx.io/accounts/${this.form.chainENU}`,
        //       class: 'enu',
        //       img: '../static/img/entrusted/enu.png',
        //     },
        //   ]
        // },
        // {
        //   value: 5,
        //   name: 'FIBOS',
        //   label: this.form.chainFIBOS,
        //   chainType: `FIBOS${this.$t('bosChain.chain')}`,
        //   options: [
        //     {
        //       name: 'fibos',
        //       url: `https://explorer.fibos.rocks/accounts/${this.form.chainFIBOS}`,
        //       class: 'enu',
        //       img: '../static/img/entrusted/fibos.png',
        //     },
        //   ]
        // },
        {
          value: 5,
          name: 'WAX',
          label: this.form.chainWAX1,
          chainType: `WAX${this.$t('bosChain.chain')}`,
          options: [
            {
              name: 'bloks',
              url: `https://wax.bloks.io/account/${this.form.chainWAX1}`,
              class: 'bloks',
              img: '../static/img/entrusted/bloks.png',
            },
          ]
        },
        {
          value: 6,
          name: 'LYNX',
          label: this.form.chainLYNX1,
          chainType: `LYNX${this.$t('bosChain.chain')}`,
          options: [
            {
              name: 'bloks',
              url: `https://lynx.bloks.io/account/${this.form.chainLYNX1}`,
              class: 'bloks',
              img: '../static/img/entrusted/bloks.png',
            },
          ]
        }
      ]
      if (this.$appName === 'tronNewdex') {
        chain = 'tron';
        this.wtOptions = [
          {
            value: 1,
            name: 'TRON',
            label: this.form.chainTRON1,
            chainType: `TRON${this.$t('bosChain.chain')}`,
            options: [
              {
                name: 'tron',
                url: `https://tronscan.org/#/contract/${this.form.chainTRON}`,
                class: 'tron',
                img: '../static/img/entrusted/tron.png',
              },
              {
                name: 'trxpl',
                url: `https://www.trxplorer.io/contract/${this.form.chainTRON}`,
                class: 'trxpl',
                img: '../static/img/entrusted/trxpl.png',
              },
            ]
          },
        ]
      }
      if (!checked && checked !== 0) {
        checked = this.wtOptions.findIndex(v => v.name.toLowerCase() === chain);
      }
      this.chainChecked = this.wtOptions[checked || 0];
    },

    // newdexiocold
    handleIocoldAction() {
      this.$refs.iocold.click();
    },

    // 委托账户下拉框选择事件
    handleCheckOption(val) {
      this.handleWeiTuoList(val - 1);
    },
    // 选择公链弹窗
    handleChoiceCurrent() {
      if (this.$route.name !== 'index') return;
      const choiceChainTip = localStorage.getItem('choiceChainTip');
      const hostname = (window.location.hostname).split('.');
      const isDingji = hostname.length === 2;
      const port = window.location.port;
      const env = process.env.NODE_ENV;
      if (!choiceChainTip) {
        if (env === 'production' && isDingji) {
          this.choiceChainVisible = true;
        }
        if (env !== 'production' && port === '2000') {
          this.choiceChainVisible = true;
        }
      }
    },

    // 选择公链弹窗回调
    handleChoiceChain() {
      this.choiceChainVisible = false;
      localStorage.setItem('choiceChainTip', 1);
    },

    // 关闭弹窗的单独Cookies动作
    handleChoiceChainClose() {
      const hostnames = window.location.hostname.split('.');
      const size = hostnames.length;
      const domain = `.${hostnames[size - 2]}.${hostnames[size - 1]}`;
      Cookies.set('tradeCode', 'eos', { path: '/', domain, expires: 30 });
      this.handleChoiceChain();
    }
  }
};

</script>

<style lang="scss" scoped>
@import "@/assets/css/variables.scss";
#app {
  position: relative;
  min-height: 100%;
  padding-bottom: 115px;
  .nodeChoiceLayer {
    /deep/ .el-dialog {
      /deep/ .el-dialog__body {
        padding-top: 50px;
        padding-bottom: 100px;
      }
    }
  }
  .entrustAccount {
    span.fl {
      color: #278eda;
      cursor: pointer;
      margin-top: 10px;
    }
    p {
      line-height: 25px;
      text-align: left;
    }
    .jumpEosflare {
      cursor: pointer;
      &:hover {
        color: #278eda;
      }
    }
  }
  // 委托账户下拉样式
  .chainCheck {
    width: 290px;
    /deep/ .el-input__prefix {
      width: 88%;
    }
    /deep/ .el-select-dropdown__item {
      padding-right: 30px;
    }
  }

  &.pdbt330{
    padding-bottom: 371px !important;
  }

  & ~ .fixed {
    padding-top: $-header-height;
  }

  .backfix {
    font-size: 12px;
    width: 70px;
    color:#c0c4cc;
  }

  .chainFlyhybox /deep/ .el-input__inner{
    color: #666;
    padding-left: 18px;
  }

  .btn,
  .btn:focus{
    background: transparent;
    color: #278eda;
  }

  .btn:hover{
    background: #278eda;
    color: white;;
  }

  .walletLoginDiaog /deep/.el-dialog__body{
    padding-top: 10px;
    padding-bottom: 40px;
  }
}
.backBlue {
  background: transparent;
  background-image: linear-gradient(to bottom, #3248CA 0%, #0C186D 100%) !important;
}
.searchDetails {

  .changeBrowse {
    padding: 6px 0;
    p {
      padding: 6px 12px;
      cursor: pointer;
      &:hover {
        background: #e9f4fb;
      }
    }
    div {
      font-size: 12px;
      color: #999;
      padding: 6px 12px;
    }
    img {
      display: block;
      width: 100%;
    }
    .eospark {
      width: 80%;
      margin: 0 auto;
    }
    .bloks {
      width: 75%;
      margin: 0 auto;
    }
    .myeos {
      width: 45%;
      margin: 0 auto;
    }
    .tron {
      width: 65%;
      margin: 0 auto;
    }
  }
}
.theme-278EDA {
  .bgWhite {
    background: #fff !important;
  }
  .embedBackground {
    background: #fff !important;
  }
  .embedBackground1 {
    background: #F2F3F8 !important;
  }
}
.theme-1B1D27 { // 黑夜
  #app{
    .chainFlyhybox /deep/ .el-input__inner{
      color: #999;
    }
  }
  .searchDetails {
    .changeBrowse {
      background: #82848a;
      div:first-child {
        color: #000;
      }
    }
  }
}

</style>
